<template>
  <!-- 考试组件 -->
  <!-- 组件类型: 118 -->
  <div class="vy-cmp-exam">
    <div class="vy-cmp-exam-container">
      <div class="vy-cmp-exam-form">
        <div class="exam-setting-panel">
          <a-row>
            <a-col :span="3">
              <span>总分</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="6">
              <a-input
                v-model="formData.totalScore"
                @blur="blur_checkNum(formData.totalScore, 'totalScore')"
              />
            </a-col>
            <a-col :span="15" style="padding-left: 5px;">
              <label style="color: #B8B8B8;">分</label>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>通过分数</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="6">
              <a-input
                v-model="formData.passScore"
                @blur="blur_checkNum(formData.passScore, 'passScore')"
              />
            </a-col>
            <a-col :span="15" style="padding-left: 5px;">
              <label style="color: #B8B8B8;">分</label>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>时长</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="6">
              <a-input
                v-model="formData.length"
                @blur="blur_checkNum(formData.length, 'length')"
              />
            </a-col>
            <a-col :span="15" style="padding-left: 5px;">
              <label style="color: #B8B8B8;"
                >分钟 （单次考试不可超过的时长）</label
              >
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>可考次数</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="6">
              <a-input
                v-model="formData.testNum"
                @blur="blur_checkNum(formData.testNum, 'testNum')"
              />
            </a-col>
            <a-col :span="15" style="padding-left: 5px;">
              <label style="color: #B8B8B8;"
                >次
                （0表示不限次数，1代表可考一次，2代表可考两次，以此类推）</label
              >
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>间隔时间</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="6">
              <a-input
                v-model="formData.intervalTime"
                @blur="blur_checkNum(formData.intervalTime, 'intervalTime')"
              />
            </a-col>
            <a-col :span="15" style="padding-left: 5px;">
              <label style="color: #B8B8B8;"
                >分钟 （单次考试不可超过的时长）</label
              >
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>考试说明</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="21">
              <!-- 富文本编辑器 -->
              <ckeditor
                :editor="editor"
                :config="editorConfig"
                v-model="formData.testIntroduce"
              ></ckeditor>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">
              <span>组卷方式</span>&nbsp;<span style="color: red;">*</span>
            </a-col>
            <a-col :span="21">
              <a-radio-group v-model="formData.testPaperType">
                <a-radio :value="1">手工组卷</a-radio>
                <a-radio :value="2">自动组卷</a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
        </div>
        <a-form class="exam-ansinput-panel">
          <a-form-item v-if="formData.questions.length">
            <template v-for="(exam, index) in formData.questions">
              <!-- 1-单选 2-多选 3-判断 4-问答 5-打分 6-填空 9-不定项选择 -->
              <template v-if="exam.type == '1'">
                <vy-cmp-exam-single
                  :key="index"
                  :index="index"
                  :title="fmt_view_title(index, exam.type)"
                  :source="exam"
                  :totalscore="haveScore"
                  @del_exam="click_del_exam"
                ></vy-cmp-exam-single>
              </template>
              <template v-if="exam.type == '2'">
                <vy-cmp-exam-multi
                  :key="index"
                  :index="index"
                  :title="fmt_view_title(index, exam.type)"
                  :source="exam"
                  :totalscore="haveScore"
                  @del_exam="click_del_exam"
                ></vy-cmp-exam-multi>
              </template>
              <template v-if="exam.type == '3'">
                <vy-cmp-exam-tandf
                  :key="index"
                  :index="index"
                  :title="fmt_view_title(index, exam.type)"
                  :source="exam"
                  :totalscore="haveScore"
                  @del_exam="click_del_exam"
                ></vy-cmp-exam-tandf>
              </template>
              <template v-if="exam.type == '4'">
                <vy-cmp-exam-qanda
                  :key="index"
                  :index="index"
                  :title="fmt_view_title(index, exam.type)"
                  :source="exam"
                  :totalscore="haveScore"
                  @del_exam="click_del_exam"
                ></vy-cmp-exam-qanda>
              </template>
              <template v-if="exam.type == '6'">
                <vy-cmp-exam-tiankong
                  :key="index"
                  :index="index"
                  :title="fmt_view_title(index, exam.type)"
                  :source="exam"
                  :totalscore="haveScore"
                  @del_exam="click_del_exam"
                ></vy-cmp-exam-tiankong>
              </template>
            </template>
          </a-form-item>
          <a-form-item>
            <div class="vy-plus-panel">
              <template v-if="plusEnableClick">
                <div
                  class="vy-plus-btn"
                  @click="() => (optionShow = !optionShow)"
                >
                  <a-icon type="plus" />
                </div>
              </template>
              <template v-else>
                <div class="vy-plus-btn" style="cursor: unset;">
                  <a-icon type="plus" style="cursor: unset;" />
                </div>
              </template>
            </div>
            <div class="vy-plus-wrapper">
              <div class="vy-plus-options" v-show="optionShow">
                <div class="vy-plus-options-panel">
                  <div
                    class="vy-plus-options-item"
                    @click="click_add_exam('1')"
                  >
                    <div class="vy-plus-options-item-icon">
                      <svg
                        class="icon"
                        aria-hidden="true"
                        font-size="32"
                        color="#ffffff"
                      >
                        <use xlink:href="#iconiconfontradiobox"></use>
                      </svg>
                    </div>
                    <div class="vy-plus-options-item-desc">单选题</div>
                  </div>
                  <div
                    class="vy-plus-options-item"
                    @click="click_add_exam('2')"
                  >
                    <div class="vy-plus-options-item-icon">
                      <svg
                        class="icon"
                        aria-hidden="true"
                        font-size="32"
                        color="#ffffff"
                      >
                        <use xlink:href="#iconduoxuan"></use>
                      </svg>
                    </div>
                    <div class="vy-plus-options-item-desc">多选题</div>
                  </div>
                  <div
                    class="vy-plus-options-item"
                    @click="click_add_exam('3')"
                  >
                    <div class="vy-plus-options-item-icon">
                      <svg
                        class="icon"
                        aria-hidden="true"
                        font-size="32"
                        color="#ffffff"
                      >
                        <use xlink:href="#iconpanduanti"></use>
                      </svg>
                    </div>
                    <div class="vy-plus-options-item-desc">判断题</div>
                  </div>
                  <div
                    class="vy-plus-options-item"
                    @click="click_add_exam('4')"
                  >
                    <div class="vy-plus-options-item-icon">
                      <svg
                        class="icon"
                        aria-hidden="true"
                        font-size="32"
                        color="#ffffff"
                      >
                        <use xlink:href="#iconwenda"></use>
                      </svg>
                    </div>
                    <div class="vy-plus-options-item-desc">问答题</div>
                  </div>
                  <div
                    class="vy-plus-options-item"
                    @click="click_add_exam('6')"
                  >
                    <div class="vy-plus-options-item-icon">
                      <svg
                        class="icon"
                        aria-hidden="true"
                        font-size="32"
                        color="#ffffff"
                      >
                        <use xlink:href="#icondianping"></use>
                      </svg>
                    </div>
                    <div class="vy-plus-options-item-desc">填空题</div>
                  </div>
                </div>
              </div>
            </div>
          </a-form-item>
          <a-form-item class="vy-form-footer">
            <a-button
              type="primary"
              :disabled="!formData.questions.length"
              @click="click_save_info"
              >保存更改</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
// 考试类型关系
const exam_TYPE = {
  "1": "单选题",
  "2": "多选题",
  "3": "判断题",
  "4": "问答题",
  "6": "填空题",
};
// 考试面板实体对象
const exam_FIELD = {
  id: +new Date(), // 题目Id
  title: "", // 题目
  score: "", // 分数
  correctAnswer: null, // 正确答案
  analysis: null, // 解析
  options: [], // 选项集合
};
import ExamSingle from "./exam/single.vue"; // 单选题
import ExamMulti from "./exam/multi.vue"; // 多选题
import ExamTAndF from "./exam/tandf.vue"; // 判断题
import ExamQAndA from "./exam/qanda.vue"; // 问答题
import ExamTiankong from "./exam/tiankong.vue"; // 填空题

import CKEditor from "@ckeditor/ckeditor5-vue2";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import zh from "@ckeditor/ckeditor5-build-classic/build/translations/zh-cn.js";
import upload from "../../../../../public/upload";

const CMP_TYPE = 118; // 组件类型
export default {
  name: "vy-cmp-exam",
  data() {
    return {
      plusEnableClick: false, // 添加按钮可以点击
      optionShow: true, // 添加选项是否显示
      //ck设置
      editor: ClassicEditor,
      editorConfig: {
        language: { ui: "zh-cn", content: "zh-cn" },
        axios: this.$axios,
        extraPlugins: [upload.MyCustomUploadAdapterPlugin],
      },
      projectId: null, // 项目id
      haveScore: 0,
      scoreInit: 0,
      // 表单字段数据
      formData: {
        moduleType: CMP_TYPE,
        totalScore: "", // 总分
        passScore: "", // 通过分数
        length: "", // 时长
        testNum: "", // 可考次数
        intervalTime: "", // 间隔时间
        testIntroduce: "", // 考试说明
        testPaperType: "", // 组卷方式:1-手工 ；2-自动组卷;
        questions: [], // 题目集合
      },
    };
  },
  watch: {
    "formData.questions": {
      deep: true,
      handler(newVal, oldVal) {
        let score = this.scoreInit;
        newVal.forEach((item) => {
          let itemScore = parseInt(item.score);
          if ((!itemScore && itemScore !== 0) || itemScore < 0) {
            itemScore = 0;
          }
          score -= itemScore;
        });
        if (score < 0) {
          score = 0;
        }
        this.haveScore = score;
      },
    },
    "formData.totalScore"(newVal, oldVal) {
      if (newVal) {
        this.haveScore = parseInt(newVal);
        this.scoreInit = this.haveScore;
      } else {
        this.haveScore = 0;
        this.scoreInit = 0;
      }

      this.formData.questions.forEach((item) => {
        item.score = "";
      });
    },
  },
  mounted() {
    const params = {
      moduleType: CMP_TYPE,
      projectId: this.projectId,
      moduleId: this.getModuleId(), // 主题Id
      id: this.formData.id || "",
    };
    this.$axios.get("/subassembly/getModuleRule", { params }).then((res) => {      
      if (res.success) {
        let result = {
          style: -1,
          use: [],
        };
        result.style = res.subassemblyVo.showQuestion;
        if (res.subassemblyVo.disorganize) {
          result.use.push("disorganize");
        }
        if (res.subassemblyVo.answerOrder) {
          result.use.push("answerOrder");
        }
        if (res.subassemblyVo.showCorrent) {
          result.use.push("showCorrent");
        }
        if (res.subassemblyVo.showScore) {
          result.use.push("showScore");
        }
        if (res.subassemblyVo.viewResult) {
          result.use.push("viewResult");
        }
        if (res.subassemblyVo.showAnalysis) {
          result.use.push("showAnalysis");
        }                
        this.$emit("exam-rule-value", result);
      }
    });
  },
  components: {
    [ExamSingle.name]: ExamSingle,
    [ExamMulti.name]: ExamMulti,
    [ExamTAndF.name]: ExamTAndF,
    [ExamQAndA.name]: ExamQAndA,
    [ExamTiankong.name]: ExamTiankong,
    ckeditor: CKEditor.component,
  },
  methods: {
    // 格式化添加的子组件标题
    fmt_view_title(index, type) {
      return `问题${index + 1}【${exam_TYPE[type]}】`;
    },
    // 添加考试-实现方法
    add_exam(type) {
      let _exam = JSON.parse(JSON.stringify(exam_FIELD));
      Object.assign(_exam, {
        type: type,
      });
      this.formData.questions.push(_exam);
    },
    // 校验数字
    blur_checkNum(val, field) {
      if (!/^[0-9]*$/.test(val)) {
        this.$message.error("请输入数字");
        this.formData[field] = "";
        return;
      }
    },
    // 点击添加考试
    click_add_exam(type) {
      this.add_exam(type);
    },
    // 删除当前考试
    click_del_exam(index) {
      this.formData.questions.splice(index, 1);
    },
    // 获取主题信息
    getModuleId() {
      return this.themeTab && this.themeTab.id;
    },
    /**
     * 判断非空，返回true表示空，false表示非空
     */
    checkEmpty() {
      if (this.formData.totalScore <= 0) {
        this.$message.error("请设置总分");
        return true;
      }
      if (this.formData.passScore <= 0) {
        this.$message.error("请设置通过分数");
        return true;
      }
      if (this.formData.length <= 0) {
        this.$message.error("请设置时长");
        return true;
      }
      if (this.formData.testNum == "") {
        this.$message.error("请设置可考次数");
        return true;
      }
      if (this.formData.intervalTime < 0) {
        this.$message.error("请设置间隔时间");
        return true;
      }
      if (!this.formData.testIntroduce) {
        this.$message.error("请设置考试说明");
        return true;
      }
      if (!this.formData.testPaperType) {
        this.$message.error("请设置组卷方式");
        return true;
      }
      // 有具体考试项
      if (this.formData.questions.length) {
        let emptyFlag = false;
        // 判断考试项非空
        for (let idx = 0; idx < this.formData.questions.length; idx++) {
          const ques = this.formData.questions[idx];
          if (!ques.title) {
            this.$message.error(`请设置【问题${idx + 1}】的考试题目`);
            emptyFlag = true;
            break;
          }
          if (!ques.correctAnswer) {
            this.$message.error(`请设置【问题${idx + 1}】的考试正确答案`);
            emptyFlag = true;
            break;
          }
          if (ques.options) {
            for (let index = 0; index < ques.options.length; index++) {
              const option = ques.options[index];
              if (!option.answer) {
                this.$message.error(`请设置【问题${idx + 1}】的考试选项内容`);
                emptyFlag = true;
                break;
              }
            }
          }
        }
        return emptyFlag;
      }
    },
    // 创建/更新内容组件
    saveInfo() {
      let params = Object.assign({}, this.formData, {
        moduleType: CMP_TYPE,
        projectId: this.projectId,
        moduleId: this.getModuleId(), // 主题Id
      });
      // delete params.content;
      if (this.checkEmpty()) {
        return;
      }
      this.$axios.post("/subassembly/save", params).then((res) => {
        if (res.success) {
          this.$message.success(res.msg);
          setTimeout(() => {
            // 查询已创建的主题模块
            // this.$parent.$parent.queryModuleInfo(CMP_TYPE);
            this.$bus.emit("refreshThemeList"); // 监听主题列表刷新事件
          }, 500);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 保存更改
    click_save_info() {
      this.saveInfo();
    },
  },
};
</script>

<style type="text/css" lang="scss">
.vy-cmp-exam {
  width: 100%;
  height: 100%;
  background: #ffffff;
  .vy-cmp-exam-container {
    .vy-cmp-exam-form {
      .exam-setting-panel {
        padding: 10px 0 30px;
        .ant-row {
          padding: 5px 0px;
        }
        .ck-editor__editable {
          height: 230px;
        }
      }

      .score-content,
      .score-content-input {
        display: flex;
        align-items: center;

        input {
          margin-right: 10px;
        }
      }

      .score-content-tip {
        color: #bab7b7;
      }

      .score-content-number {
        margin: 0 5px;
        color: #96b1ff;
      }
      .exam-ansinput-panel {
        input.ant-input {
          border: none;
          border-bottom: 1px solid #d9d9d9;
          border-radius: 0;
          + .ant-input-group-addon {
            border: none;
            border-bottom: 1px solid #d9d9d9;
            border-radius: 0;
            background-color: transparent;
          }
        }

        input.ant-input-normal {
          border: 1px solid #d9d9d9;
          border-radius: 4px;
        }
        // 考试内容填写展示区域
        .vy-cmp-exam-item {
          border: 1px dashed #e8e7e7;
          margin-bottom: 10px;
        }
        // 考试类型区域添加
        .vy-plus-panel {
          position: relative;
          &::before {
            content: " ";
            position: absolute;
            top: 50%;
            left: 10px;
            right: 10px;
            height: 1px;
            border-top: 1px solid #494949;
          }
          .vy-plus-btn {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #ffffff;
            padding: 0 20px;
            z-index: 10;
            cursor: pointer; // 若是可点击显示隐藏添加考试类型选项，可设置该值
            .anticon-plus {
              padding: 5px;
              background: #494949;
              border-radius: 50%;
              color: #ffffff;
            }
          }
        }
        .vy-plus-wrapper {
          position: relative;
          width: fit-content;
          margin: 0 auto;
          // border: 1px solid red;
          .vy-plus-options {
            margin: 0 auto;
            padding-top: 32px;
            position: relative;
            &::before {
              position: absolute;
              content: " ";
              border: 10px solid #494949;
              border-color: #fff #fff #494949 #fff;
              top: 12px;
              left: calc(50% - 10px);
            }
            .vy-plus-options-panel {
              border: 1px solid #000000;
              display: flex;
              border-radius: 8px;
              color: #ffffff;
              background: #494949;
              justify-content: space-between;
              .vy-plus-options-item {
                line-height: initial;
                position: relative;
                text-align: center;
                cursor: pointer;
                padding: 8px;
                box-shadow: 0px 0px 10px 2px rgba(87, 87, 87, 0.14);
                .vy-plus-options-item-desc {
                  padding-top: 6px;
                  font-size: 14px;
                  font-weight: 400;
                }
              }
            }
          }
        }
      }
    }
  }
  .vy-form-footer {
    margin-top: 50px;
    text-align: center;
    margin-bottom: 0;
    .ant-btn {
      padding: 0 100px;
      &.ant-btn-primary {
        background: rgba(51, 102, 255, 1);
        &:hover {
          background: rgba(51, 102, 255, 0.8);
        }
        &[disabled] {
          background: #f5f5f5;
          &:hover {
            background: #f5f5f5;
          }
        }
      }
    }
  }
}
</style>
